define([
  'jquery',
  'underscore',
  'models/AlertMessage',
  'views/View',
  'hbs!template/upload/upload'
], function($, _, AlertMessage, View, template){
  var UploadView = View.extend({
    events: {
      "change #fileToUpload":        "fileSelected",
      "click input[name=upload]":    "uploadFile",
      "click input[name=cancel]":    "cancelSelection"
    },
    
    initialize: function(options) {
      options = options || {};
      
      View.prototype.initialize(options);
      this.template = template;
      _.bindAll(this,
                'uploadProgress',
                'uploadComplete',
                'uploadFailed',
                'uploadCanceled');
    },

    render: function() {
      $(this.el).html(this.template({file: this.file}));
      return this;
    },

    fileSelected: function() {
      console.log("File selected!!!");
      var file = document.getElementById('fileToUpload').files[0];
      if (file) {
        this.file = file;
      }
      this.render();
    },

    cancelSelection: function() {
      // Delete file
      delete this.file;
      this.render();
    },

    uploadFile: function(f){
      console.log("UploadFile!!!");
      var file = f || this.file;

      if(file) {
        // Create a form data
        var fd = new FormData();
        fd.append("file", file);

        // Create the XMLHttpRequest
        var xhr = new XMLHttpRequest();

        // Add events listeners
        xhr.upload.addEventListener("progress", this.uploadProgress, false);
        xhr.addEventListener("load", this.uploadComplete, false);
        xhr.addEventListener("error", this.uploadFailed, false);
        xhr.addEventListener("abort", this.uploadCanceled, false);

        // Send data
        xhr.open("POST", "/upload/");
        xhr.send(fd);
      }
    },

    uploadProgress: function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
        var progressBar = document.getElementById("uploadProgress");
        if(progressBar) {
          progressBar.value = percentComplete;
        }
        //$("#uploadProgress").attr("value", percentComplete);
      }
      else {
        console.log("Fail to get the percent from evt.");
      }
    },
    uploadComplete: function(){
      var message = new AlertMessage({title: "Upload completed!", content: "The file was uploaded.", type: "info"});
      this.addMessage(message);
      // Delete file
      this.cancelSelection();
    },
    uploadFailed: function(){
      console.log("upload failed!!");
      var message = new AlertMessage({title: "Upload Failed!", content: "The file upload failed.", type: "error"});
      this.addMessage(message);
    },
    uploadCanceled: function(){
      console.log("upload canceled!!");
    }
  });

  return UploadView;
});